package service

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"video_rpc/basic/config"
	__ "video_rpc/basic/proto"
	"video_rpc/handler/model"
)

type Server struct {
	//__.UnimplementedGreeterServer
	__.UnimplementedVideoServer
}

func (s *Server) VideosAdd(_ context.Context, in *__.VideosAddReq) (*__.VideosAddResp, error) {

	video := model.Videos{
		VideosUrl: in.VideosUrl,
		Episode:   in.Episode,
		Duration:  in.Duration,
		VideoName: in.VideoName,
		Status:    in.Status,
		Type:      in.Type,
		Label:     in.Label,
	}
	if len(in.VideoName) <= 100 {
		return nil, fmt.Errorf("视频标题过长")
	}
	err := video.VideosAdd(config.DB)
	if err != nil {
		return nil, fmt.Errorf("视频添加失败")
	} else {
		fmt.Println("视频添加成功")
	}

	return &__.VideosAddResp{
		VideoId: strconv.Itoa(int(video.ID)),
	}, nil
}

func (s *Server) ReviewAdd(_ context.Context, in *__.ReviewAddReq) (*__.ReviewAddResp, error) {

	review := model.Review{
		VideosId:     int(in.VideosId),
		Status:       strconv.FormatInt(in.Status, 10),
		Opinion:      in.Opinion,
		ReviewName:   in.ReviewName,
		ReviewNumber: in.ReviewNumber,
	}

	err := review.ReviewAdd(config.DB)
	if err != nil {
		return nil, fmt.Errorf("审核视频发送失败")
	} else {
		fmt.Println("审核视频发送成功")
	}
	marshal, err := json.Marshal(review)
	if err != nil {
		return nil, err
	}
	config.Rdb.Set(config.Ctx, "VideoKey", marshal, time.Minute*30)
	return &__.ReviewAddResp{
		ReviewId: strconv.Itoa(int(review.ID)),
	}, nil
}

func (s *Server) VideosUpdate(_ context.Context, in *__.VideosUpdateReq) (*__.VideosUpdateResp, error) {

	video := model.Videos{}

	err := video.VideoUpdate(config.DB, int(video.ID), int(in.Status))
	if err != nil {
		return nil, fmt.Errorf("视频审核失败")
	} else {
		fmt.Println("视频审核成功")
	}

	return &__.VideosUpdateResp{
		ReviewId: strconv.Itoa(int(video.ID)),
	}, nil
}
